import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { routerRedux } from 'dva/router';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import {
  Row,
  Col,
  Card,
  Icon,
  Tooltip,
  Form,
  Input,
  Button,
  Switch,
  Radio,
  message,
  BackTop,
  Spin,
} from 'antd';
import Editor from '@/utils/Editor';
import styles from '@/pages/Account/robotSetup/index.less';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
import Bottword from '@/modules/Bottword.js';
import ljx from '../../../assets/icons/垃圾箱.png';
import xy from '@/assets/account/robotSetup/xy.png';
import sy from '@/assets/account/robotSetup/sy.png';
import laji from '@/assets/account/robotSetup/laji.png';
import xztime from '@/assets/account/robotSetup/xztime.png';
import qdbuttom from '@/assets/account/robotSetup/qdbuttom.png';
import qxbuttom from '@/assets/account/robotSetup/qxbuttom.png';
import onImg from '@/assets/knowledge/on.png';
import offImg from '@/assets/knowledge/off.png';
import RobotBtn from '@/utils/robotBtn';

class NewRobot extends Component {
  constructor(props) {
    super(props);
    this.state = {
      content: '',
      commonProblemList: [{ name: '', item: '' }],
      pdxs: true,
      valueA: '1',
      Chat: null,
      BaiKe: null,
      CommunityQA: null,
      Chatpd: false,
      BaiKepd: false,
      CommunityQApd: false,
      timedaan: '',
      list: {},
      hyy: '',
      enableChat: false,
      login: false,
      valueMax: false,
      valueMaxa: false,
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    // this.fetchc();
  }

  switchA = a => {
    // 闲聊知识库
    console.log(a);
    this.setState({ enableChat: a });
  };

  //  --------------------热门问题-----------------
  handleAdditem = () => {
    if (this.state.commonProblemList.length > 9) {
      message.error('常见问题最多可以添加10个');
    } else {
      this.setState(
        a => ({
          commonProblemList: [...a.commonProblemList, { name: '' }],
        }),
        () => {
          let a = this.state.commonProblemList;
          console.log(a);
          for (var i = 0; i < a.length - 1; i++) {
            console.log(a[i]);
            a[i].name = 'tcx';
          }
          console.log(a);
          this.setState({ commonProblemList: a }, () => {
            const { input } = this.inputRef; // 如果是textArea的话，const { textAreaRef } = this.inputRef;
            input.focus();
            input.setSelectionRange(0, input.value.length);
          });
          // }
        }
      );
    }
  };

  handleSubmitAs = e => {
    console.log(e);
    let a = this.state.commonProblemList;
    a.splice(e, 1);
    console.log(a);
    this.setState({ commonProblemList: a });
  };

  // 上移
  handleSubmitAyd = index => {
    console.log(index);
    let arr = this.state.commonProblemList;
    this.upData(arr, index);
  };

  upData = (arr, index) => {
    var swapItems = function(arr, index1, index2) {
      arr[index1] = arr.splice(index2, 1, arr[index1])[0];
      return arr;
    };
    var newArr = [];
    if (arr.length > 1 && index !== 0) {
      newArr = swapItems(arr, index, index - 1);
    }
    console.log('数据', newArr);
    if (newArr.length === 0) {
      message.info(`再上移就没了`);
    } else {
      this.setState({ commonProblemList: newArr });
    }
  };

  // 上移结束

  zjrmwt = (e, b) => {
    console.log(e.target.value, b);
    let a = this.state.commonProblemList;
    a[b].item = e.target.value;
    this.setState({ commonProblemList: a });
  };

  onChangeValue = e => {
    this.setState({
      valueA: e.target.value,
    });
  };

  rktbonChange = e => {
    console.log(`switch to ${e}`);
    if (e === true) {
      this.setState({
        valueA: '1',
        valueMaxa: false,
        valueMax: true,
      });
    }
    if (e === false) {
      this.setState({
        // valueA: '2',
        valueMaxa: true,
        valueMax: false,
      });
    }
  };

  rktbonChangea = e => {
    console.log(`switch to ${e}`);
    if (e === true) {
      this.setState({
        valueA: '2',
        valueMaxa: true,
        valueMax: false,
      });
    }
    if (e === false) {
      this.setState({
        // valueA: '2',
        valueMaxa: false,
        valueMax: true,
      });
    }
  };

  cancel = () => {
    const { dispatch } = this.props;
    dispatch(
      routerRedux.push({
        pathname: '/overviewRobots',
        params: {},
      })
    );
  };


  checkField=(rule, value, callback)=>{
    var regu = "^[ ]+$";
    var reg = new RegExp(regu);
    console.log(value,rule.field);
    if(rule.field === 'userName'){
      if(value){
        if(reg.test(value))
        {
          callback('机器人昵称不符合要求，请重新输入')
        }else{
          callback()
        }
      }else{
        callback('')
      }
    }else if(rule.field === 'unknownAnswer'){
      if(value){
        if(reg.test(value))
        {
          callback('未知问题回答不符合要求，请重新输入')
        }else{
          callback()
        }
      }else{
        callback('')
      }
    }

  };

  // eslint-disable-next-line react/sort-comp
  render() {
    const { getFieldDecorator } = this.props.form;
    const FormItemLayont = {
      labelCol: {
        sm: 24,
        md: 24,
      },
      wrapperCol: {
        sm: 24,
        md: 14,
      },
    };
    const FormItemLayontA = {
      labelCol: {
        md: 24,
        lg: 2,
      },
      wrapperCol: {
        md: 24,
        lg: 14,
      },
    };
    const FormItemLayontB = {
      labelCol: {
        md: 24,
        lg: 2,
      },
      wrapperCol: {
        md: 24,
        lg: 16,
      },
    };
    const displayp = {
      display: 'none',
    };
    return (
      <div>
        <div>
          <p style={{ marginTop: 10 }} className={styles.pageTitle}>
            新建机器人
          </p>
          <Spin spinning={this.state.login}>
            {/* <Row className={styles.colorBackground}>
              <Col style={{ padding: 10 }} xs={24}>
                <div className={styles.title}>
                  <span>基础设置</span>
                </div>
              </Col>
            </Row> */}
            <div className="homecard">
              <Card className={styles.dabj} bordered={false}>
                <Form className="zdyfroma" layout="horizontal">
                  <FormItem label="昵称" {...FormItemLayont}>
                    {getFieldDecorator('userName', {
                      validateTrigger: ['onChange', 'onBlur'],
                      initialValue: this.state.list.name,
                      rules: [
                        {
                          required: true,
                          message: '请填写机器人昵称',
                        },
                        {
                          validator: this.checkField,
                        }
                      ],
                    })(<Input />)}
                  </FormItem>
                  {/* <FormItem label="性别" {...FormItemLayont}>
                  {getFieldDecorator('gender', {
                    initialValue: this.state.list.gender,
                    rules: [
                      {
                        required: true,
                        message: '请填写机器人性别',
                      },
                    ],
                  })(<Input />)}
                </FormItem>
                <FormItem label="介绍" {...FormItemLayont}>
                  {getFieldDecorator('introduce', {
                    initialValue: this.state.list.introduction,
                    rules: [
                      {
                        required: true,
                        message: '请填写机器人介绍',
                      },
                    ],
                  })(<Input />)}
                </FormItem> */}
                  <FormItem className="editor" label="欢迎语" {...FormItemLayont}>
                    {/* {this.state.valueMax ? (
                      <img
                        src={onImg}
                        style={{ cursor: 'pointer', width: 30, marginTop: 5 }}
                        alt=""
                        onClick={() => this.rktbonChange(false)}
                      />
                    ) : (
                      <img
                        src={offImg}
                        style={{ cursor: 'pointer', width: 30, marginTop: 5 }}
                        alt=""
                        onClick={() => this.rktbonChange(true)}
                      />
                    )}
                    <span style={{ color: '#1D1D1D', marginLeft: 10, marginRight: 10 }}>
                      用以下内容作为欢迎语
                    </span>
                    {this.state.valueMaxa ? (
                      <img
                        src={onImg}
                        style={{ cursor: 'pointer', width: 30, marginTop: 5 }}
                        alt=""
                        onClick={() => this.rktbonChangea(false)}
                      />
                    ) : (
                      <img
                        src={offImg}
                        style={{ cursor: 'pointer', width: 30, marginTop: 5 }}
                        alt=""
                        onClick={() => this.rktbonChangea(true)}
                      />
                    )}

                    <span style={{ color: '#1D1D1D', marginLeft: 10 }}>
                      用以下问题的答案作为欢迎语
                    </span> */}
                    <RadioGroup onChange={this.onChangeValue} value={this.state.valueA}>
                      <Radio value="1">用以下内容作为欢迎语</Radio>
                      <Radio value="2">用以下问题的答案作为欢迎语</Radio>
                    </RadioGroup>
                    <div style={{ height: 5 }} />
                    <div style={this.state.valueA !== '1' ? displayp : null}>
                      <Editor
                        content={this.state.content}
                        name="content"
                        id="content"
                        // height="300"
                        width="500"
                        ref={r => (this.ueditor = r)}
                      />
                    </div>
                    {getFieldDecorator('hyy', {
                      initialValue: this.state.hyy,
                    })(
                      <Input
                        onChange={this.timedaan}
                        style={this.state.valueA !== '2' ? displayp : null}
                        placeholder=""
                      />
                    )}
                  </FormItem>
                  {/* <FormItem label="常见问题" {...FormItemLayontA} /> */}
                  <p style={{ color: '#c8c8c8' }}>常见问题</p>
                  <div className={styles.flexMapa}>
                    {this.state.commonProblemList.map((item, index) => {
                      return (
                        <span
                          style={{ width: 290, marginRight: 10 }}
                          className={styles.flexMap}
                          key={index}
                        >
                          <Input
                            ref={
                              this.state.commonProblemList.length - 1 === index
                                ? input => {
                                    this.inputRef = input;
                                  }
                                : 'a'
                            }
                            onPressEnter={this.handleAdditem}
                            value={item.item}
                            onChange={e => this.zjrmwt(e, index)}
                            placeholder=""
                          />
                          {item.name === '' ? null : (
                            <span className={styles.qnmb}>
                              {/* <Icon
                              onClick={() => this.handleSubmitAyd(index)}
                              type="arrow-up"
                              style={{ marginLeft: 5, width: 14, padding: '14px 0px 9px 0px' }}
                            /> */}
                              <span onClick={() => this.handleSubmitAyd(index)}>
                                <img style={{ position: 'relative', top: 9 }} src={sy} />
                              </span>

                              <span style={{ marginLeft: 5 }}>
                                <img
                                  src={laji}
                                  style={{ cursor: 'pointer', position: 'relative', top: 9 }}
                                  onClick={() => this.handleSubmitAs(index)}
                                />
                              </span>
                            </span>
                          )}
                        </span>
                      );
                    })}
                    {/* <Button onClick={this.handleAdditem}>新增常见问题</Button> */}
                    <span>
                      <img
                        style={{ cursor: 'pointer', position: 'relative', top: 2 }}
                        onClick={this.handleAdditem}
                        src={xztime}
                      />
                    </span>
                  </div>
                  <FormItem label="未知问题回答">
                    {getFieldDecorator('unknownAnswer', {
                      validateTrigger: ['onChange', 'onBlur'],
                      initialValue: this.state.list.defaultAnswer,
                      rules: [
                        {
                          required: true,
                          message: '请填写机器人未知问题回答',
                        },
                        {
                          validator: this.checkField,
                        }
                      ],
                    })(<Input placeholder="" />)}
                  </FormItem>
                </Form>
                <div className={styles.flexcen}>
                  <div>
                    <img onClick={this.cancel} src={qxbuttom} style={{ marginRight: 50 }} />
                    <img onClick={this.saveFrom} src={qdbuttom} />
                  </div>
                </div>
              </Card>
            </div>
            <p />
            {/* <Row className={styles.colorBackground}>
              <Col style={{ padding: 10 }} xs={24}>
                <div className={styles.title}>
                  <span>功能设置</span>
                </div>
              </Col>
            </Row>
            <Card bordered={false}>
              <Form layout="horizontal">
                <FormItem label="闲聊知识库" {...FormItemLayontA}>
                  <Switch
                    onChange={this.switchA}
                    checkedChildren="开"
                    unCheckedChildren="关"
                    checked={this.state.enableChat}
                  />
                </FormItem>
              </Form>
              <div style={{ height: 50 }} />
              <div className="backtop">
                <BackTop visibilityHeight={-100}>
                  <Button type="primary" onClick={this.saveFrom} style={{ marginRight: 10 }}>
                    保存
                  </Button>
                </BackTop>
              </div>
            </Card> */}
          </Spin>
        </div>
      </div>
    );
  }

  timedaan = e => {
    console.log(e.target.value);
    this.setState({ timedaan: e.target.value });
  };

  saveFrom = () => {
    let a = this.state.commonProblemList;
    let b = [];
    a.map(item => {
      b.push(item.item);
    });

    console.log(b);

    const { timedaan } = this.state;
    console.log(this.ueditor.getUeditorContent()); // 富文本
    const welcomeInfo = {};
    welcomeInfo.welcomeType = Number(this.state.valueA);
    if (this.state.valueA == '1') {
      this.setState({ timedaan: '' });
      if (this.ueditor.getUeditorContent()) {
        welcomeInfo.content = this.ueditor.getUeditorContent();
      } else {
        message.error('欢迎语不能为空');
        return;
      }
    } else {
      this.setState({ content: '' });
      if (this.state.timedaan) {
        welcomeInfo.content = timedaan;
      } else {
        message.error('欢迎语不能为空');
        return;
      }
    }

    let userInfo = this.props.form.getFieldsValue(); // 获取数据
    this.props.form.validateFields((err, values) => {
      // 校验方法
      console.log(userInfo);
      var reg = "^[ ]+$";
      if (!err) {
        // if(!reg.test(userInfo.userName)){
        //   return message.info('机器人昵称不能为空')
        // }
        // if(!reg.test(userInfo.unknownAnswer)){
        //   return message.info('未知问题回答不能为空')
        // }

        const { dispatch, currentUser } = this.props;
        const RobotVo = {
          name: userInfo.userName,
          gender: '男',
          introduction: '你好',
          defaultAnswer: userInfo.unknownAnswer,
          enableChat: this.state.enableChat,
          commonQuestion: b,
          welcomeInfo,
          userId: currentUser.uid,
        };
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'newRobot/robotAddRobot',
            payload: RobotVo,
            callback: res => {
              console.log('列表数据1', res);
              if (res.code == 0) {
                message.success(`${res.msg}`);
                dispatch(
                  routerRedux.push({
                    pathname: '/overviewRobots',
                    params: {},
                  })
                );
              } else {
                message['error'](`参数错误`);
              }
            },
          });
        });
      }
    });
  };

  fetchc = () => {
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'newRobot/fetchc',
        //  payload: { id: currentUser.robotId },
        payload: {},
        callback: res => {
          console.log('列表数据', res);
          if (res.commonQuestion[0] !== '') {
            console.log('12345');
            let b = [];
            let a = res.commonQuestion;
            a.map((item, index) => {
              let c = { name: '', item: '' };
              c.name = 'tcx';
              c.item = item;
              b.push(c);
            });
            console.log(b);
            this.setState({ commonProblemList: b });
          }

          if (res.welcomeInfo.welcomeType === 1) {
            this.setState({
              content: res.welcomeInfo.content,
            });
          } else {
            this.setState({
              hyy: res.welcomeInfo.content,
              timedaan: res.welcomeInfo.content,
            });
          }
          console.log(res.features);
          if (String(res.welcomeInfo.welcomeType) === '1') {
            this.setState({ valueMax: true, valueMaxa: false });
          }
          if (String(res.welcomeInfo.welcomeType) === '2') {
            this.setState({ valueMax: false, valueMaxa: true });
          }
          this.setState({
            list: res,
            valueA: String(res.welcomeInfo.welcomeType),
            enableChat: res.enableChat,
            login: false,
          });
        },
      });
    });
  };
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(NewRobot));
